package com.b2c.erp.controller.goods;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.b2c.entity.ContactEntity;
import com.b2c.entity.DataRow;
import com.b2c.entity.ErpGoodsPublishRecordEntity;
import com.b2c.entity.SupplierGoodsEntity;
import com.b2c.entity.api.ApiResult;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.erp.enums.ContactTypeEnum;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.vo.DyOrderImportOrderVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.controller.CommonControllerUtils;
import com.b2c.interfaces.ErpGoodsPublishRecordService;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.SupplierGoodsService;
import com.b2c.interfaces.WmsUserService;
import com.b2c.interfaces.wms.ContactService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.google.gson.JsonObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商商品报价信息
 */
@Controller
public class GoodsInfoSupplierController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ErpGoodsPublishRecordService recordService;
    @Autowired
    private ContactService contactService;
    @Autowired
    private WmsUserService manageUserService;
    @Autowired
    private SupplierGoodsService supplierGoodsService;
    private static Logger log = LoggerFactory.getLogger(GoodsInfoSupplierController.class);
    @RequestMapping(value = "/goods/info_list_for_supplier", method = RequestMethod.GET)
    public String getList(Model model, HttpServletRequest request) {

        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        String number = null;
        if (!StringUtils.isEmpty(request.getParameter("number"))) {
            number = request.getParameter("number");
        }
        model.addAttribute("number",number);
        Integer supplierId = null;
        if (!StringUtils.isEmpty(request.getParameter("supplierId"))) {
            supplierId = Integer.parseInt(request.getParameter("supplierId"));
        }
        model.addAttribute("supplierId",supplierId);
        Integer publishStatus = null;
        if (!StringUtils.isEmpty(request.getParameter("publishStatus"))) {
            publishStatus = Integer.parseInt(request.getParameter("publishStatus"));
        }
        model.addAttribute("publishStatus",publishStatus);
        Boolean publishStatusB = null;
        if(publishStatus!=null && publishStatus == 1) publishStatusB = true;
        else if (publishStatus!=null && publishStatus == 0)publishStatusB = false;

        var result = supplierGoodsService.getList(pageIndex,pageSize,number,supplierId,publishStatusB);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());
        // 获取供应商
        List<ContactEntity> supplierList = contactService.getList(ContactTypeEnum.Supplier);
        model.addAttribute("supplierList", supplierList);

//        var permissionKey = "spgl";
//        model.addAttribute("view", permissionKey);
//        model.addAttribute("pView", "sale");
        CommonControllerUtils.setViewKey(model,manageUserService,"spgl");
        return "goods/goods_info_for_supplier";
    }

    @RequestMapping(value = "/goods/goods_publish_to_shops", method = RequestMethod.GET)
    public String editShops(Model model,@RequestParam Integer id, HttpServletRequest request) {
        //店铺列表
        List<DcShopEntity> shops = shopService.getShopList(null);
        model.addAttribute("shops", shops);

        model.addAttribute("goodsId", id);
        return "goods/goods_supplier_publish_to_shops";
    }

    @ResponseBody
    @RequestMapping(value = "/goods/goods_publish_to_shops_ajax", method = RequestMethod.POST)
    public com.b2c.erp.response.ApiResult<Integer> editPostAjax(Model model, @RequestBody DataRow data, HttpServletRequest request) {

        Integer goodsId = data.getInt("goodsId");
        if(goodsId == null ) return new com.b2c.erp.response.ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少id");


        String publishDate = data.getString("publishDate");
        String shopIds = data.getString("shopIds");




        recordService.publishToShop(goodsId,shopIds,publishDate);

        return new com.b2c.erp.response.ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS");
    }
    @ResponseBody
    @RequestMapping(value = "/goods/edit_attr3_ajax", method = RequestMethod.POST)
    public ApiResult<String> orderRemark(HttpServletRequest req,@RequestBody DataRow reqData) throws Exception {
        Integer id = reqData.getInt("id");
        String attr3 = reqData.getString("attr3");

        log.info("修改attr3......................"+attr3);

        supplierGoodsService.updateAttr3(id,attr3);

        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS" );
    }

    @ResponseBody
    @RequestMapping(value = "/goods/info_list_for_supplier_review_ajax", method = RequestMethod.POST)
    public ApiResult<List<SupplierGoodsEntity>> orderSendExcel(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        System.out.println(destFileName);

        Integer supplierId = Integer.parseInt(req.getParameter("supplierId"));
        Workbook workbook = null;


        File destFile = new File(destFileName);

        if (destFile.exists()) {
            destFile.deleteOnExit();
        }
        file.transferTo(destFile);
        log.info("/***********导入供应商商品报价信息，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");

        InputStream fis = null;
        fis = new FileInputStream(destFileName);
        if (fis == null) return new ApiResult<>(502, "没有文件");

        try {
            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            // workbook = new HSSFWorkbook(fis);


        } catch (Exception ex) {
            log.info("/***********导入供应商商品报价信息***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }


        //删除文件
        if (destFile.exists()) {
            destFile.deleteOnExit();
        }

        if (workbook == null) return new ApiResult<>(502, "未读取到Excel文件");


        /****************导入供应商商品报价信息****************/
        //订单list
        List<SupplierGoodsEntity> list = new ArrayList<>();
        Sheet sheet = null;

        try {
            sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();//最后一行索引
            Row row = null;
//            Map<String, PictureData> maplist = null;
//            maplist = getPictures2((XSSFSheet) sheet);

            for (int i = 1; i <= lastRowNum; i++) {
                row = sheet.getRow(i);
                SupplierGoodsEntity entity = new SupplierGoodsEntity();
                String goodsNo = "";//货号
                try {
                    goodsNo = row.getCell(1).getStringCellValue().replace("\t", "");
                } catch (Exception e) {
                    goodsNo = row.getCell(1).getNumericCellValue() + "";
                    goodsNo = goodsNo.replace(".0","");
                }
                if (StringUtils.hasText(goodsNo)) {
                    String color = row.getCell(2).getStringCellValue().replace("\t", "");
                    String size = row.getCell(3).getStringCellValue().replace("\t", "");
                    String price = "";//价格
                    try {
                        price = row.getCell(4).getStringCellValue().replace("\t", "");
                    } catch (Exception e) {
                        price = row.getCell(4).getNumericCellValue() + "";
                    }
                    if(StringUtils.hasText(price)==false){
                        price = "0.0";
                    }
                    String tanli = row.getCell(6).getStringCellValue().replace("\t", "");
                    String mianliao = row.getCell(7).getStringCellValue().replace("\t", "");
                    String panUrl = row.getCell(9).getStringCellValue().replace("\t", "");
                    String panPwd = "";
                    try {
                        panPwd = row.getCell(10).getStringCellValue().replace("\t", "");
                    } catch (Exception e) {
                        panPwd = row.getCell(10).getNumericCellValue() + "";
                    }
                    entity.setNumber(goodsNo);
                    entity.setSize(size);
                    entity.setColor(color);
                    entity.setPrice(price);
                    entity.setAttr1(tanli);
                    entity.setAttr2(mianliao);
                    entity.setPanUrl(panUrl);
                    entity.setPanPwd(panPwd);
                    entity.setSupplierId(supplierId);
                    entity.setRemark(row.getCell(11).getStringCellValue().replace("\t", ""));
                    var result = supplierGoodsService.insert(entity);
                    if (result == null) {
                        log.info("重复：" + JSONObject.toJSONString(entity));
                    } else {
                        list.add(result);
                        log.info("添加成功" + JSON.toJSONString(result));
                    }
                }
            }

        } catch (Exception ex) {
            log.info("/***********导入供应商商品信息***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        return new ApiResult<>(0, "SUCCESS", list);
    }

    public static void saveImg(PictureData picData, String filePath) {

        if (picData == null) {
            //System.out.println(key + " 无图 " + filePath);
            return;
        }
//        System.out.println(key + " 有图 " + filePath);
        byte[] data = picData.getData();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            out.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, PictureData> getPictures2 (XSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "execl_img" + File.separator ;
        //获取图片列表
        List<XSSFShape> list = sheet.getDrawingPatriarch().getShapes();
        //对表格进行操作i
        for (int i = 0; i < sheet.getDrawingPatriarch().getShapes().size(); i++) {
            XSSFShape shape = list.get(i);
            XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
            if (shape instanceof XSSFPicture) {
                XSSFPicture pic = (XSSFPicture) shape;
                //获取列编号
                int col = anchor.getCol2();
                XSSFPictureData picData = pic.getPictureData();
                map.put(getImgKey(i, col), picData);

                String fileName =  destFileName+ i+"-"+col+".jpeg";
                saveImg(picData,fileName);
            }
        }
//        List<POIXMLDocumentPart> list = sheet.getRelations();
//        for (POIXMLDocumentPart part : list) {
//            if (part instanceof XSSFDrawing) {
//                XSSFDrawing drawing = (XSSFDrawing) part;
//                List<XSSFShape> shapes = drawing.getShapes();
//                for (XSSFShape shape : shapes) {
//                    XSSFPicture picture = (XSSFPicture) shape;
//                    try {
//                        XSSFClientAnchor anchor = picture.getPreferredSize();
//                        CTMarker marker = anchor.getFrom();
//                        String key = marker.getRow() + "-" + marker.getCol();
//                        map.put(key, picture.getPictureData());
//                    }catch (Exception e){
//                        map.put("a", null);
//                    }
//                }
//            }
//        }
        return map;
    }
    private static String getImgKey(int row, int col) {
        return row + ":" + col;
    }

}
